import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'
import InputWithLabel from './InputWithLabel'
import CheckboxInput from './CheckboxInput'
import TextInput from './TextInput'
import TextareaInput from './TextareaInput'
import SelectInput from './SelectInput'
import Layers from './Layers'
import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL_MALL } from '../publicAPI/publicAPI'

class MallCouponEditor extends Component {
	constructor (props, context) {
	    super(props, context)
	    console.log("初始化");
	   
	    this.state = {	
	    	hasBeenMounted: false,
	        delete: false,
	        deleteId: -1,
	        status:1,//2修改，1新增
	        couponName:'',
	        clazzStr:'',
	        clazzId:'',
	        errorM1:'',
	        errorM:'',
	        select_show:'none',

	        disabled:false,
	        submitBtn:'block',
	        modifyBtn:'none',
	        deleteBtn:'none',

	        FixedDiscount:0,
	        showFixed: false,
	    } ;// 初始化状态

	}

	componentWillMount() {
	     console.log("将安装");

	     if (this.props.params.id != undefined) {
	         //    根据参数获取数据
	         
	         console.log('-----',this.props.params.id);
	         this.setState({
	         	disabled:true,
	           submitBtn:'none',
	           modifyBtn:'block',
	           deleteBtn:'block',

	         });

	         if (!this.state.hasBeenMounted && this.props.params.id){
	             console.log('set finished');
	             this.handleGetInfo();
	         }
	     }else{
	         this.setState({
	         	disabled:false,
	           submitBtn:'block',
	           modifyBtn:'none',
	           deleteBtn:'none',

	         });
	     }
	}

	handleGetInfo(){
		var URL = ROOTURL_MALL + 'kabuy/coupon/type/instance.api';
		var _this = this;
		var param = {
			id: this.props.params.id
		};
		fetch(URL,{
		    method: 'POST',
		    mode: "cors",
		    body: JSON.stringify(param)
		}).then(function (res) {
		    	if(res.ok){
		    	    res.json().then(data=>{
		    	        console.log(data);
		    	        	 if(data.clazz==".fixed"){
		    	        	 	  _this.setState({
		    	        	 	  		clazzStr:"打折",
		    	        	 	  		showFixed: true
		    	        	 	  })
		    	        	 }else if(data.clazz==".free"){
		    	        	 	  _this.setState({
		    	        	 	  		clazzStr: "免费",
		    	        	 	  		showFixed: false
		    	        	 	  })
		    	        	 }
		    	        	 // if(data.meta!=undefined&&data.meta!=null){
		    	        	 // 	 if(data.meta.clazzName!=undefined&&data.meta.clazzName!=null){
		    	        	 // 	 		_this.setState({
		    	        	 // 	 		    clazzStr: data.meta.clazzName,
		    	        	 // 	 		})
		    	        	 // 	 }
		    	        	 // }
		    	        	 if(data.meta!=undefined&&data.meta!=null){
		    	        	 		if(data.meta.FixedDiscount!=undefined&&data.meta.FixedDiscount!=null){
	    	        	 				_this.setState({
	    	        	 				    FixedDiscount: data.meta.FixedDiscount
	    	        	 				})
		    	        	 		}
		    	        	 }
		    	            _this.setState({
		    	                couponName: data.dname,
		    	                clazzId: data.meta.clazz,
		    	            })
		    	        console.log(_this.state)
		    	    })
		    	}
		});
	}

	componentDidMount() {
	    console.log("安装成功");  
	}

	handleSubmit(e){
		if(this.state.clazzId == ''){
			this.setState({
				 errorM:'',
				 errorM1 : '请务必选择免费还是打折！',
				 errorM2:""
			})
		}else if(this.state.couponName == ''){
			this.setState({
				 errorM1:'',
				 errorM : '请填写优惠券类型名称！',
				 errorM2:""
			})
		}else if(this.state.clazzId == ".fixed" && this.state.FixedDiscount==""){
			this.setState({
				 errorM:"",
				 errorM1: "",
				 errorM2: "请填写减免价格！"
			})
		}else{
			this.setState({
				 errorM1 : '',
				 errorM : ''
			})
			var URL = ROOTURL_MALL + 'kabuy/coupon/type/instance.api';
			if(this.state.status == 1){
				var param = {
					dname: this.state.couponName,
					clazz: this.state.clazzId,
					stValid: true,
					meta:{
						clazzName: this.state.clazzStr,
						FixedDiscount: parseInt(this.state.FixedDiscount)
					},
					// smeta:{
					// 	FixedDiscount:{
					// 		d: parseInt(this.state.FixedDiscount)
					// 	}
					// }
				};

				fetch(URL,{
				    method: 'POST',
				    mode: 'cors',
				    body: JSON.stringify(param)
				}).then(function (res) {
				    if (res.ok){
				    	alert('添加成功！');
				        window.location.href="/MallCoupon";
				    }else{
				        alert('添加失败！可能有重名了！');
				    }
				});
			}else if(this.state.status == 2){
				var param = {
					dname: this.state.couponName,
					id: this.props.params.id,
					clazz: this.state.clazzId,
					stValid: true,
					meta:{
						clazzName: this.state.clazzStr,
						FixedDiscount: parseInt(this.state.FixedDiscount)
					},
					// smeta:{
					// 	FixedDiscount:{
					// 		d: parseInt(this.state.FixedDiscount)
					// 	}
					// }
				};
				alert(parseInt(this.state.FixedDiscount))
				fetch(URL,{
				    method: 'POST',
				    mode: 'cors',
				    body: JSON.stringify(param)
				}).then(function (res) {
				    if (res.ok){
				    	alert('修改成功！');
				        window.location.href="/MallCoupon";
				    }else{
				        alert('修改失败！可能有重名了！');
				    }
				});
			}
		}
		
	}

	inputTClick(e){
		const selectValue = e.target.innerText
		if(selectValue=="免费"){
			this.setState({
				 clazzId:'.free',
				 showFixed: false
			})
		}else if(selectValue=="打折"){
			this.setState({
				 clazzId:'.fixed',
				 showFixed: true
			})
		}
		this.setState({select_show: "none", clazzStr: selectValue})
	}

	inputFocus() {
	    this.setState({select_show: "block"})
	}

	handleModify(e){
		this.setState({
			disabled:false,
			submitBtn:'block',
			modifyBtn:'none',
			deleteBtn:'none',
			status:2
		})
	}

	handleDelete(id){
		this.setState({
			delete: !this.state.delete,
			deleteId: id
		})
	}

	deleteType(){
		var _this = this;
		var param = {
		  // id:this.state.deleteId
		}
		   var URL1 = ROOTURL_MALL + 'kabuy/coupon/type/instance.api?id=' + this.state.deleteId;
		   fetch(URL1,{
		       method: 'DELETE',
		       mode: "cors",
		       body: param
		   }).then(function (res) {
		       if (res.ok){
		           console.log('delete success');
		           window.location.href="/MallCoupon";
		       }else{
		           console.log(res)
		       }
		   });
		   this.setState({
		       delete: !this.state.delete
		   });
	}

	render(){
		return (

			<div className="right-wapper ">
			    <div className="rt-wrap" style={{border:'none'}}>
			        <div className="right-wrap">
			            <div className="wrap" style={{paddingBottom:"40px"}}>

					            <div className={style["input_div"]} style={{position:'relative'}}>
					                <label style={{marginRight:"20px"}}>免费/打折</label>
					                <input inputId="clazzStr" disabled={this.state.disabled} className="default-text" placeholder="" value={this.state.clazzStr} readOnly onFocus={() => this.inputFocus()} onChange={val=>this.setState(Object.assign({},this.state, {clazzStr: val}))}/>&nbsp;&nbsp;
					                <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM1}</span>
					                <ul  className="input_select" style={{display: this.state.select_show,left:"100px"}}>
					                  <li onClick={(e) => this.inputTClick(e)}>免费</li>
					                  <li onClick={(e) => this.inputTClick(e)}>打折</li>
					                </ul>
					            </div>

			                <div className={style["input_div"]} style={{margin:'20px 0 20px'}}>
			                    <label style={{marginRight:"20px"}}>名称</label>
			                    <TextInput inputId="couponName"  disabled={this.state.disabled} placeHolder="请输入优惠券名称" val={this.state.couponName} onChange={val=>this.setState(Object.assign({}, this.state, {couponName: val}))}/>&nbsp;&nbsp;
			                     <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM}</span>
			                </div>
			                {
			                	this.state.showFixed?  
					                	<div className={style["input_div"]} style={{margin:'20px 0 40px'}}>
					                    <label style={{marginRight:"20px"}}>特定减</label>
					                    <TextInput inputId="FixedDiscount"  disabled={this.state.disabled} placeHolder="" val={this.state.FixedDiscount} onChange={val=>this.setState(Object.assign({}, this.state, {FixedDiscount: val}))} style={{width:"100px"}}/>&nbsp;&nbsp;元
					                     <span style={{marginBottom:'20px',marginLeft:'2px',color:'red'}}>{this.state.errorM2}</span>
					                	</div> : null
			                }
			               


			                <span id="hint"/>
			                <button id="submit" className={style["main_btn"]} onClick={(e) => this.handleSubmit(e) }  style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.submitBtn}}>保存</button>
			                <button id="modify" className={style["main_btn"]} style={{backgroundColor: '#2285c7',float:'left',border: '1px solid #1e77b3',display: this.state.modifyBtn,marginLeft:'12px'} } onClick={  (e) => this.handleModify(e) }>修改</button>
			                <button id="delete" className={style["main_btn"]} style={{backgroundColor: '#f2846f',float:'left',border: '1px solid #d55c44',display: this.state.deleteBtn,marginLeft:'12px'} } onClick={ (e) =>this.handleDelete(this.props.params.id) }>删除</button>
			                
			                <Link to={`/MallCoupon`}>
			                     <button id="back" className={style["main_btn"]}  style={{backgroundColor: '#2285c7',border: '1px solid #1e77b3',marginLeft:'12px'}}>返回</button>
			                </Link>
			            </div>
			        </div>
			    </div>
			    { this.state.delete ?
			      <div id={style.msgDialog}>
			        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
			          <div className={style['msgDialog_button']}>
			            <button id={style['msgDialog_yes']} onClick={this.deleteType.bind(this)}>确定</button>
			            <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
			          </div>
			        </div>
			      </div> : null}
			</div>
		)
	}
}


export default MallCouponEditor